//
//  ViewController.swift
//  Swift_SRSocket
//
//  Created by lantaiyuan on 2017/8/21.
//  Copyright © 2017年 lantaiyuan. All rights reserved.
//

import UIKit
import SocketRocket
class ViewController: UIViewController,SRWebSocketDelegate {

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var msgTextfield: UITextField!
    @IBOutlet weak var sendMsgBtn: UIButton!
    //懒加载
    private
    var websocket : SRWebSocket?
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        self.reConnect()
    }
    private func reConnect() {
       websocket?.delegate = nil
       websocket?.close()
       websocket = nil
      websocket = SRWebSocket.init(urlRequest: URLRequest.init(url: URL.init(string: "http://localhost:8181")!, cachePolicy: .reloadRevalidatingCacheData, timeoutInterval: 2.0))
        websocket?.delegate = self as SRWebSocketDelegate
        websocket?.open()
    }
    /* 发送socket*/
    @IBAction func msgAction(_ sender: UIButton) {
      self.view.endEditing(true)
        if let websoc = websocket {
            websoc.send(self.msgTextfield.text!)
        }
    }
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        websocket?.delegate = nil
        websocket?.close()
        websocket = nil
    }
    /*SRWebSocketDelegate */
    func webSocket(_ webSocket: SRWebSocket!, didReceiveMessage message: Any!) {
        if webSocket.readyState == .OPEN {
            self.label.text = message as? String
        }
    }
    func webSocket(_ webSocket: SRWebSocket!, didFailWithError error: Error!) {
        print("\(error!.localizedDescription)")
    }
    func webSocketDidOpen(_ webSocket: SRWebSocket!) {
        print("连接成功")
    }
    func webSocket(_ webSocket: SRWebSocket!, didCloseWithCode code: Int, reason: String!, wasClean: Bool) {
        print("链接关闭")
        websocket = nil
        
    }
    func webSocket(_ webSocket: SRWebSocket!, didReceivePong pongPayload: Data!) {

    }

    @IBAction func closeAction(_ sender: UIButton) {
    
        websocket?.delegate = nil
        websocket?.close()
        websocket = nil
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

